#include "NetworkThread.h"
#include "TcpSocketViewerProtocol.h"
#include "config.h"
#include <iostream>

using namespace std;

void error(const char *msg)
{
	perror(msg);
	exit(0);
}

void PrintMatrixSexy(float *m)
{
	puts("Printing Matrix in a sexy way!\n");
	for (int i = 0; i < 4; ++i)
	{
		printf("|");
		for (int j = 0; j < 4; ++j)
		{
			printf("%2.2f ", m[i * 4 + j]);
		}
		printf("|\n");
	}
	printf("\n");
}

void NetworkThread::run()
{
	frameRate = 30;
	float *m;
	ViewerProtocol *protocol = new ViewerProtocolImplementation();

	protocol->connect("127.0.0.1");

	int sleepTime = 1000000 / frameRate;

	while (1)
	{
		int x;
		try
		{
			puts("Going to receive data!");
			x = protocol->receive();
			puts("Data received!");
		} catch (NetworkException ex)
		{
			puts("Failed to receive stuff!\n");
			return;
		}
		switch (x)
		{
		case ViewerProtocol::CHANGE_ELEMENTS:
		{
			puts("getLocations:");
			char* bla = new char[30];
			time_t timestamp = time(NULL);
			;
			strftime(bla, 30, "%H:%M:%S: ", localtime(&timestamp));
			puts(bla);
			m = protocol->getLocationData();
			int c = protocol->getCount();
			printf("%d\n", c);
			//			for (int i = 0; i < c; ++i)
			//			{
			//				PrintMatrixSexy(m + i * 16 * 4);
			//			}

			//if (c)
				emit modsign(m);

			printf("getLocations done\n");
			break;
		}
		}
		usleep(sleepTime);
	}
}
